using System;
using System.Collections.Generic;
using System.Configuration;
using System.Runtime.ExceptionServices;
using System.Web;

[assembly: WebActivator.PreApplicationStartMethod(typeof(CreatureSoft.Hoot.Web.AppStart_RegisterMonitoring), "Start")]
namespace CreatureSoft.Hoot.Web {
    public static class AppStart_RegisterMonitoring {
        public static void Start() {
            SetupMonitoring();
        }
        public static readonly string _item = "__RequestExceptionKey";

        private static void SetupMonitoring()
        {
            bool appDomainMonitoringEnabled, firstChanceExceptionMonitoringEnabled;
            bool.TryParse(ConfigurationManager.AppSettings["AppDomainMonitoringEnabled"], out appDomainMonitoringEnabled);
            bool.TryParse(ConfigurationManager.AppSettings["FirstChanceExceptionMonitoringEnabled"], out firstChanceExceptionMonitoringEnabled);
            if (appDomainMonitoringEnabled)
            {
                AppDomain.MonitoringIsEnabled = true;
            }
            if (firstChanceExceptionMonitoringEnabled)
            {		
                AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e) =>
                {
                    if (HttpContext.Current == null)// If no context available, ignore it
                        return;
                    if (HttpContext.Current.Items[_item] == null)
                        HttpContext.Current.Items[_item] = new RequestException { Exceptions = new List<Exception>() };
                    (HttpContext.Current.Items[_item] as RequestException).Exceptions.Add(e.Exception);		    
                };
		Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(MonitorAspNetApplicationModule));
            }            
        } 
    }
}